﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.Entity;

public partial class System_PopupOrganizationUser :PageBase
{
    OrgainzationManager orgManager = new OrgainzationManager();
    private const string NameControl_Id = "NameControlId";
    private const string ValueControl_Id = "ValueControlId";
    private const string UserListControl_ID = "UserListControlID";
    private const string ChainsControl_ID = "ChainsControlID";
    private const string Select_Type = "SelectType";
    private const string RegionControl_ID = "CountyControlID";
    private const string txtCount_ID = "txtCountID";
    private string nameControl;
    private string valueControl;
    private string userListControl;
    private string chainsControl;
    private string regionControl;
    private string selectType;
    private string txtCountID;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString[NameControl_Id] != null)
        {
            nameControl = Request.QueryString[NameControl_Id];
        }
        if (Request.QueryString[ValueControl_Id] != null)
        {
            valueControl = Request.QueryString[ValueControl_Id];
        }
        if (Request.QueryString[UserListControl_ID] != null)
        {
            userListControl = Request.QueryString[UserListControl_ID];
        }
        if (Request.QueryString[ChainsControl_ID] != null)
        {
            chainsControl = Request.QueryString[ChainsControl_ID];
        }
        if (Request.QueryString[Select_Type] != null)
        {
            selectType = Request.QueryString[Select_Type];
        }
        if (Request.QueryString[RegionControl_ID] != null)
        {
            regionControl = Request.QueryString[RegionControl_ID];
        }
        if (Request.QueryString[txtCount_ID] != null)
        {
            txtCountID = Request.QueryString[txtCount_ID];
        }
        btnOK.OnClientClick = "Submit(this)";

        if (!IsPostBack)
        {
            BindTree();
        }
    }

    private void BindTree()
    {
        TreeOrg.Nodes.Clear();
        DataTable dt = orgManager.SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, "and ACTIVE=1");
        DataRow[] rows = dt.Select("level=1");
        foreach (DataRow row in rows)
        {
            TreeNode node = new TreeNode();
            node.Text = row["name"].ToString();
            node.Value = row["id"].ToString();
            node.SelectAction = TreeNodeSelectAction.Expand;
            node.ShowCheckBox = true;
            
            if (selectType.ToLower() == "single")
                TreeOrg.Attributes.Add("onClick", "SingleCheck()");
            else
                TreeOrg.Attributes.Add("onClick", "client_OnTreeNodeChecked()");

            AddSubNode(node, dt);
            TreeOrg.Nodes.Add(node);
        }
        TreeOrg.CollapseAll();

    }

    private void AddSubNode(TreeNode node, DataTable dt)
    {
        AddChildUser(node);
        DataRow[] rows = dt.Select("parentid=" + node.Value);
        foreach (DataRow row in rows)
        {
            TreeNode ChildNode = new TreeNode();
            ChildNode.Text = row["name"].ToString();
            ChildNode.Value = row["id"].ToString();
            ChildNode.SelectAction = TreeNodeSelectAction.Expand;
            ChildNode.ShowCheckBox = true;
           
            //AddChildUser(ChildNode);
            AddSubNode(ChildNode, dt);
           
            node.ChildNodes.Add(ChildNode);
        }
    }
    private void AddChildUser(TreeNode node)
    {
        DataTable dt = PersonManager.SelectPERSONSsDynamic(
                                                                   "",
                                                                    "-1",
                                                                    "",
                                                                    MyStateManager.DomainID,
                                                                    "'"+node.Value+"'",
                                                                    "1",1
                                                                   ).Tables[0];
        TreeNode n = null;

        foreach(DataRow dr in dt.Rows)
        {
            n=new TreeNode(dr["NAME"].ToString(),"user"+dr["ID"].ToString());
            n.ShowCheckBox = true;
            n.ImageUrl = "../css/zTreeStyle/img/user.png";
            node.ChildNodes.Add(n);
        }
    }
    protected void btnOK_Click(object sender, EventArgs e)
    {
        //组织的名字
        string names = string.Empty;

        //部门的值
        string values = string.Empty;

        //巡店督导
        string mobileUserList = string.Empty;

        //经销商
        string chainsList = string.Empty;

        //行政架构
        string regionList = string.Empty;

        //选中人数
        int count=0;
        //遍历树获取选中节点
        foreach (TreeNode node in TreeOrg.CheckedNodes)
        {
            
            if (node.Checked&&node.Value.StartsWith("user"))
            {
                names += node.Text + ",";
                values +=node.Value.Substring(4) + ",";
                count++;
            }
        }

        names = names.TrimEnd(',');
        values = values.TrimEnd(',');
        this.OrgShowValue = names;
        this.OrgHidValue = values;
        if (names == string.Empty)
        {
            Response.Write("<script>window.close();</script>");
            return;
        }

        //根据部门获取巡店督导
        DataTable dtUser = new MobileUserManager().Load(MyStateManager.DomainID, values);
        foreach (DataRow row in dtUser.Rows)
            mobileUserList += row["ID"] + "∞" + row["CODENAME"] + "∮";
        mobileUserList = mobileUserList.TrimEnd('∮');

        //根据部门获取市场等级行政架构
        DataTable dtCounty = new RegionManager().GetRegionTable("", values, (int)RegionLevel.county, "", MyStateManager.DomainID);
        string regionId = "";
        foreach (DataRow row in dtCounty.Rows)
        {
            regionList += row["ID"] + "∞" + row["DISTRICT_NAME"] + "∮";
            regionId += row["ID"].ToString() + ",";
        }
        regionList = regionList.TrimEnd('∮');
        this.RegionHidValue = regionList;

        //根据行政架构(市场等级)获取经销商
        if (!"".Equals(regionId))
        {
            DataTable dt = new ChainManager().GetChainTable(MyStateManager.DomainID,"", "", "1");
            foreach (DataRow row in dt.Rows)
                chainsList += row["ID"] + "∞" + row["DESCRIPTION"] + "∮";
            chainsList = chainsList.TrimEnd('∮');
        }
        this.ChainHidValue = chainsList;
        
        //生成js脚本并传回父窗体
        StringBuilder str = new StringBuilder();
        str.AppendLine("<script language='javascript'>");
        //str.AppendLine(" alert('" + nameControl + "');alert(window.opener.document.getElementById('" + nameControl + "'));");

        //回传部门名称
        if (!string.IsNullOrEmpty(nameControl))
            str.AppendLine("    window.opener.document.getElementById('" + nameControl + "').value=\"" + names + "\";");

        //回传部门数值
        if (!string.IsNullOrEmpty(valueControl))
            str.AppendLine("    window.opener.document.getElementById('" + valueControl + "').value=\"" + values + "\";");

        //回传数量
        if (!string.IsNullOrEmpty(txtCountID))
            str.AppendLine("    window.opener.document.getElementById('" + txtCountID + "').value=\"" + count + "\";");

        //回传巡店督导
        if (!string.IsNullOrEmpty(userListControl))
            str.AppendLine("    window.opener.document.getElementById('" + userListControl + "').value=\"" + mobileUserList + "\";");

        //回传经销商
        if (!string.IsNullOrEmpty(chainsControl))
            str.AppendLine("    window.opener.document.getElementById('" + chainsControl + "').value=\"" + chainsList + "\";");

        //回传行政架构(市场等级)
        if (!string.IsNullOrEmpty(regionControl))
            str.AppendLine("    window.opener.document.getElementById('" + regionControl + "').value=\"" + regionList + "\";");

        str.AppendLine("   window.opener.document.forms[0].submit();");
        str.AppendLine("   window.close()");
        str.AppendLine("</script>");

        Response.Write(str.ToString());
    }
    protected void TreeOrg_SelectedNodeChanged(object sender, EventArgs e)
    {
        if (TreeOrg.SelectedNode.Expanded==true)
            TreeOrg.SelectedNode.Collapse();
        else
            TreeOrg.SelectedNode.Expand();
    }
}
